/*
 *  Copyright 2019-2023 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.yangxu.hospital.system.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.domain.Person;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.beust.ah.A;
import com.yangxu.hospital.common.utils.FileUtil;
import com.yangxu.hospital.common.utils.PageResult;
import com.yangxu.hospital.common.utils.PageUtil;
import com.yangxu.hospital.common.utils.SecurityUtils;
import com.yangxu.hospital.system.modules.system.domain.AppointmentSlots;
import com.yangxu.hospital.system.modules.system.domain.DoctorSchedule;
import com.yangxu.hospital.system.modules.system.domain.SysDoctor;
import com.yangxu.hospital.system.modules.system.domain.User;
import com.yangxu.hospital.system.modules.system.domain.dto.DoctorScheduleDto;
import com.yangxu.hospital.system.modules.system.mapper.AppointmentSlotsMapper;
import com.yangxu.hospital.system.modules.system.mapper.UserMapper;
import com.yangxu.hospital.system.modules.system.service.AppointmentSlotsService;
import com.yangxu.hospital.system.modules.system.service.SysDoctorService;
import com.yangxu.hospital.tools.utils.TimeUtils;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangxu.hospital.system.modules.system.service.DoctorScheduleService;
import com.yangxu.hospital.system.modules.system.domain.vo.DoctorScheduleQueryCriteria;
import com.yangxu.hospital.system.modules.system.mapper.DoctorScheduleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @description 服务实现
 * @author 杨旭
 * @date 2024-11-25
 **/
@Service
@RequiredArgsConstructor
public class DoctorScheduleServiceImpl extends ServiceImpl<DoctorScheduleMapper, DoctorSchedule> implements DoctorScheduleService {

    private final DoctorScheduleMapper doctorScheduleMapper;
    private final UserMapper userMapper;
    private final SysDoctorService sysDoctorService;
    private final AppointmentSlotsService appointmentSlotsService;
    private final AppointmentSlotsMapper appointmentSlotsMapper;

    @Override
    public PageResult<DoctorSchedule> queryAll(DoctorScheduleQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(doctorScheduleMapper.findAll(criteria, page));
    }

    @Override
    public List<DoctorSchedule> queryAll(DoctorScheduleQueryCriteria criteria){
        return doctorScheduleMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(DoctorSchedule resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DoctorSchedule resources) {
        DoctorSchedule doctorSchedule = getById(resources.getScheduleId());
        doctorSchedule.copy(resources);
        saveOrUpdate(doctorSchedule);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<DoctorSchedule> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DoctorSchedule doctorSchedule : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("医生ID", doctorSchedule.getDoctorId());
            map.put("创建时间", doctorSchedule.getCreateTime());
            map.put("更新时间", doctorSchedule.getUpdateTime());
            map.put("是否上午（1: 是, 0: 否）", doctorSchedule.getIsMorning());
            map.put("是否下午（1: 是, 0: 否）", doctorSchedule.getIsAfternoon());
            map.put("上午开始时间", doctorSchedule.getMorningStartTime());
            map.put("上午结束时间", doctorSchedule.getMorningEndTime());
            map.put("下午开始时间", doctorSchedule.getAfternoonStartTime());
            map.put("下午结束时间", doctorSchedule.getAfternoonEndTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

//    public ResponseEntity<Object> addDoctorSchedule(Map<String, Object> param) {
//        List doctorDatas = (List) param.get("doctorDatas");
//        param.remove("doctorDatas");
//        List<String> scheduleDates = (List<String>) param.get("scheduleDate");
//        param.remove("scheduleDate");
//        List<DoctorSchedule> doctorSchedules = new ArrayList<>();
//        doctorDatas.forEach(e ->{
//            for (String s : scheduleDates) {
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义与日期字符串匹配的格式
//                LocalDate date = LocalDate.parse(s, formatter);
//                DoctorSchedule doctorSchedule1 = new DoctorSchedule();
////                doctorSchedule1.;
//                BeanUtil.copyProperties(param,doctorSchedule1);
//                doctorSchedule1.setDoctorId(Long.valueOf(e.toString()));
//                doctorSchedule1.setScheduleDate(date);
//                doctorSchedules.add(doctorSchedule1);
//            }
//        });
//        // 查出当前doctorSchedules里面的日期的所有排班，如果有重复的就更新，没有就添加排班
//        List<DoctorSchedule> doctorSchedules1 = doctorScheduleMapper.selectList(new LambdaQueryWrapper<DoctorSchedule>().in(DoctorSchedule::getScheduleDate, scheduleDates));
//        ArrayList<DoctorSchedule> doctorSchedules2 = new ArrayList<>();
//        doctorSchedules1.forEach(e -> {
//            doctorSchedules.forEach(p -> {
//                if (e.getScheduleDate().equals(p.getScheduleDate()) && e.getDoctorId().equals(p.getDoctorId())) {
//                    System.out.println(e);
//                    System.out.println(p);
//                    if (p.getIsMorning()){
//                        e.setIsMorning(p.getIsMorning());
//                        e.setMorningStartTime(p.getMorningStartTime());
//                        e.setMorningEndTime(p.getMorningEndTime());
//                    }
//                    if (p.getIsAfternoon()){
//                        e.setIsAfternoon(p.getIsAfternoon());
//                        e.setAfternoonStartTime(p.getAfternoonStartTime());
//                        e.setAfternoonEndTime(p.getAfternoonEndTime());
//                    }
//                    System.out.println(e);
//                    System.out.println(p);
//                    doctorScheduleMapper.updateById(e);
//                }else {
//                    doctorSchedules2.add(p);
//                }
//
//            });
//        });
//        doctorSchedules.removeAll(doctorSchedules1);
//
//        // 添加排班
//        this.saveBatch(doctorSchedules2);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
//    public ResponseEntity<Object> addDoctorSchedule(Map<String, Object> param) {
//        List<?> doctorDatas = (List<?>) param.get("doctorDatas");
//        param.remove("doctorDatas");
//        List<String> scheduleDates = (List<String>) param.get("scheduleDate");
//        param.remove("scheduleDate");
//
//        List<DoctorSchedule> doctorSchedules = new ArrayList<>();
//
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 定义与日期字符串匹配的格式
//
//        for (Object e : doctorDatas) {
//            try {
//                Long doctorId = Long.valueOf(e.toString());
//                for (String s : scheduleDates) {
//                    LocalDate date = LocalDate.parse(s, formatter);
//                    DoctorSchedule doctorSchedule1 = new DoctorSchedule();
//                    BeanUtil.copyProperties(param, doctorSchedule1);
//                    doctorSchedule1.setDoctorId(doctorId);
//                    doctorSchedule1.setScheduleDate(date);
//                    doctorSchedules.add(doctorSchedule1);
//                }
//            } catch (NumberFormatException ex) {
//                return new ResponseEntity<>("Invalid doctorId format", HttpStatus.BAD_REQUEST);
//            } catch (Exception ex) {
//                return new ResponseEntity<>("Error processing data: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
//            }
//        }
//
//        // 查出当前doctorSchedules里面的日期的所有排班，如果有重复的就更新，没有就添加排班
//        List<DoctorSchedule> existingSchedules = doctorScheduleMapper.selectList(
//                new LambdaQueryWrapper<DoctorSchedule>()
//                        .in(DoctorSchedule::getScheduleDate, scheduleDates)
//                        .in(DoctorSchedule::getDoctorId,
//                                doctorSchedules.stream()
//                                        .map(DoctorSchedule::getDoctorId)
//                                        .collect(Collectors.toList())));
//
//        List<DoctorSchedule> schedulesToUpdate = new ArrayList<>();
//        List<DoctorSchedule> schedulesToAdd = new ArrayList<>(doctorSchedules); // 初始化为所有待添加的排班
//
//        for (DoctorSchedule newSchedule : doctorSchedules) {
//            boolean found = false;
//            for (DoctorSchedule existingSchedule : existingSchedules) {
//                if (newSchedule.getDoctorId().equals(existingSchedule.getDoctorId())
//                        && newSchedule.getScheduleDate().equals(existingSchedule.getScheduleDate())) {
//                    found = true;
//                    if (newSchedule.getIsMorning() != null && newSchedule.getIsMorning()) {
//                        existingSchedule.setIsMorning(true);
//                        existingSchedule.setMorningStartTime(newSchedule.getMorningStartTime());
//                        existingSchedule.setMorningEndTime(newSchedule.getMorningEndTime());
//                    }else {
//                        existingSchedule.setIsMorning(false);
//                        existingSchedule.setMorningStartTime(null);
//                        existingSchedule.setMorningEndTime(null);
//                    }
//                    if (newSchedule.getIsAfternoon() != null && newSchedule.getIsAfternoon()) {
//                        existingSchedule.setIsAfternoon(true);
//                        existingSchedule.setAfternoonStartTime(newSchedule.getAfternoonStartTime());
//                        existingSchedule.setAfternoonEndTime(newSchedule.getAfternoonEndTime());
//                    }else {
//                        existingSchedule.setIsAfternoon(false);
//                        existingSchedule.setAfternoonStartTime(null);
//                        existingSchedule.setAfternoonEndTime(null);
//                    }
//                    schedulesToUpdate.add(existingSchedule);
//                    break;
//                }
//            }
//            if (found) {
//                schedulesToAdd.remove(newSchedule); // 移除已经处理过的排班
//            }
//        }
//
//        // 更新已存在的排班信息
//        if (!schedulesToUpdate.isEmpty()) {
//            this.updateBatchById(schedulesToUpdate);
//            saveOrUpdateAppointmentSlots(schedulesToUpdate);
//        }
//
//        // 添加新的排班信息
//        if (!schedulesToAdd.isEmpty()) {
//            this.saveBatch(schedulesToAdd);
//            saveOrUpdateAppointmentSlots(schedulesToAdd);
//        }
//
//        return new ResponseEntity<>(HttpStatus.OK);
//    }
//
//    /**
//     * 保存或更新排号信息表
//     * @param doctorSchedules 医生日程安排列表
//     */
//    public void saveOrUpdateAppointmentSlots(List<DoctorSchedule> doctorSchedules) {
//        // 查询现有的排号数据
//        List<AppointmentSlots> existingSlots = appointmentSlotsService.list();
//        Map<String, List<AppointmentSlots>> existingMap = new HashMap<>();
//        for (AppointmentSlots slot : existingSlots) {
//            String key = generateKey(slot.getDoctorId(), slot.getDepartmentId(), slot.getScheduleDate());
//            existingMap.computeIfAbsent(key, k -> new ArrayList<>()).add(slot);
//        }
//
//        Set<AppointmentSlots> newOrUpdatedSlots = new HashSet<>();
//        Set<Long> slotsToDelete = new HashSet<>();
//
//        // 查出所有的医生
//        List<SysDoctor> doctors = sysDoctorService.list();
//
//        // 遍历每个医生的日程安排
//        for (DoctorSchedule doctorSchedule : doctorSchedules) {
//            // 过滤出当前医生的信息
//            Optional<SysDoctor> doctorOptional = doctors.stream()
//                    .filter(e -> doctorSchedule.getDoctorId().equals(e.getDoctorId()))
//                    .findFirst();
//
//            if (!doctorOptional.isPresent()) {
//                continue; // 如果找不到医生，跳过当前日程安排
//            }
//
//            SysDoctor doctor = doctorOptional.get();
//
//            // 处理上午时间段
//            if (doctorSchedule.getIsMorning()) {
//                LocalTime morningStartTime = doctorSchedule.getMorningStartTime();
//                LocalTime morningEndTime = doctorSchedule.getMorningEndTime();
//
//                Map<Integer, String> dailySchedule = TimeUtils.getDailySchedule(
//                        doctorSchedule.getScheduleDate(),
//                        morningStartTime,
//                        morningEndTime,
//                        doctor.getIntervalMinutes());
//
//                String key = generateKey(doctorSchedule.getDoctorId(), doctor.getDepartmentId(), doctorSchedule.getScheduleDate());
//                List<AppointmentSlots> existingSlotsForDate = existingMap.getOrDefault(key, Collections.emptyList());
//
//                // 删除旧的排号时间
//                slotsToDelete.addAll(existingSlotsForDate.stream()
//                        .map(AppointmentSlots::getId)
//                        .collect(Collectors.toList()));
//
//                for (Map.Entry<Integer, String> entry : dailySchedule.entrySet()) {
//                    AppointmentSlots slot = new AppointmentSlots();
//                    slot.setDoctorId(doctorSchedule.getDoctorId());
//                    slot.setScheduleDate(doctorSchedule.getScheduleDate());
//                    slot.setDepartmentId(doctor.getDepartmentId());
//                    slot.setAppointmentTime(entry.getValue().toString());
//                    slot.setIsMorning(doctorSchedule.getIsMorning());
//                    slot.setRowNum(entry.getKey());
//                    newOrUpdatedSlots.add(slot);
//                }
//            }
//
//            // 处理下午时间段
//            if (doctorSchedule.getIsAfternoon()) {
//                LocalTime afternoonStartTime = doctorSchedule.getAfternoonStartTime();
//                LocalTime afternoonEndTime = doctorSchedule.getAfternoonEndTime();
//
//                Map<Integer, String> dailySchedule = TimeUtils.getDailySchedule(
//                        doctorSchedule.getScheduleDate(),
//                        afternoonStartTime,
//                        afternoonEndTime,
//                        doctor.getIntervalMinutes());
//
//                String key = generateKey(doctorSchedule.getDoctorId(), doctor.getDepartmentId(), doctorSchedule.getScheduleDate());
//                List<AppointmentSlots> existingSlotsForDate = existingMap.getOrDefault(key, Collections.emptyList());
//
//                // 删除旧的排号时间
//                slotsToDelete.addAll(existingSlotsForDate.stream()
//                        .map(AppointmentSlots::getId)
//                        .collect(Collectors.toList()));
//
//                for (Map.Entry<Integer, String> entry : dailySchedule.entrySet()) {
//                    AppointmentSlots slot = new AppointmentSlots();
//                    slot.setDoctorId(doctorSchedule.getDoctorId());
//                    slot.setScheduleDate(doctorSchedule.getScheduleDate());
//                    slot.setDepartmentId(doctor.getDepartmentId());
//                    slot.setAppointmentTime(entry.getValue());
//                    slot.setIsAfternoon(doctorSchedule.getIsAfternoon());
//                    slot.setRowNum(entry.getKey());
//                    newOrUpdatedSlots.add(slot);
//                }
//            }
//        }
//        // 删除旧的排号时间
//        if (!slotsToDelete.isEmpty()) {
//            appointmentSlotsMapper.deleteBatchIds(slotsToDelete);
//        }
//
//        // 保存或更新批量预约时间段
//        appointmentSlotsService.saveBatch(newOrUpdatedSlots);
//    }
//
//    /**
//     * 生成唯一的键用于标识排号记录
//     * @param doctorId 医生ID
//     * @param departmentId 科室ID
//     * @param scheduleDate 排班日期
//     * @return 唯一键
//     */
//    private String generateKey(Long doctorId, Long departmentId, LocalDate scheduleDate) {
//        return doctorId + "-" + departmentId + "-" + scheduleDate.toString();
//    }

    public ResponseEntity<Object> addDoctorSchedule(Map<String, Object> param) {
        List<?> doctorDatas = (List<?>) param.get("doctorDatas");
        param.remove("doctorDatas");
        List<String> scheduleDates = (List<String>) param.get("scheduleDate");
        param.remove("scheduleDate");

        List<DoctorSchedule> doctorSchedules = new ArrayList<>();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        for (Object e : doctorDatas) {
            try {
                Long doctorId = Long.valueOf(e.toString());
                for (String s : scheduleDates) {
                    LocalDate date = LocalDate.parse(s, formatter);
                    DoctorSchedule doctorSchedule1 = new DoctorSchedule();
                    BeanUtil.copyProperties(param, doctorSchedule1);
                    doctorSchedule1.setDoctorId(doctorId);
                    doctorSchedule1.setScheduleDate(date);
                    doctorSchedules.add(doctorSchedule1);
                }
            } catch (NumberFormatException ex) {
                return new ResponseEntity<>("Invalid doctorId format", HttpStatus.BAD_REQUEST);
            } catch (Exception ex) {
                return new ResponseEntity<>("Error processing data: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }

        // 查出当前doctorSchedules里面的日期的所有排班，如果有重复的就更新，没有就添加排班
        List<DoctorSchedule> existingSchedules = doctorScheduleMapper.selectList(
                new LambdaQueryWrapper<DoctorSchedule>()
                        .in(DoctorSchedule::getScheduleDate, scheduleDates)
                        .in(DoctorSchedule::getDoctorId,
                                doctorSchedules.stream()
                                        .map(DoctorSchedule::getDoctorId)
                                        .collect(Collectors.toList())));

        List<DoctorSchedule> schedulesToUpdate = new ArrayList<>();
        List<DoctorSchedule> schedulesToAdd = new ArrayList<>(doctorSchedules);

        for (DoctorSchedule newSchedule : doctorSchedules) {
            boolean found = false;
            for (DoctorSchedule existingSchedule : existingSchedules) {
                if (newSchedule.getDoctorId().equals(existingSchedule.getDoctorId())
                        && newSchedule.getScheduleDate().equals(existingSchedule.getScheduleDate())) {
                    found = true;
                    if (newSchedule.getIsMorning() != null && newSchedule.getIsMorning()) {
                        existingSchedule.setIsMorning(true);
                        existingSchedule.setMorningStartTime(newSchedule.getMorningStartTime());
                        existingSchedule.setMorningEndTime(newSchedule.getMorningEndTime());
                    } else {
                        existingSchedule.setIsMorning(false);
                        existingSchedule.setMorningStartTime(null);
                        existingSchedule.setMorningEndTime(null);
                    }
                    if (newSchedule.getIsAfternoon() != null && newSchedule.getIsAfternoon()) {
                        existingSchedule.setIsAfternoon(true);
                        existingSchedule.setAfternoonStartTime(newSchedule.getAfternoonStartTime());
                        existingSchedule.setAfternoonEndTime(newSchedule.getAfternoonEndTime());
                    } else {
                        existingSchedule.setIsAfternoon(false);
                        existingSchedule.setAfternoonStartTime(null);
                        existingSchedule.setAfternoonEndTime(null);
                    }
                    schedulesToUpdate.add(existingSchedule);
                    break;
                }
            }
            if (found) {
                schedulesToAdd.remove(newSchedule);
            }
        }
        // 使用线程池来处理数据库操作
        ExecutorService threadPool = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池

        // 更新已存在的排班信息
        if (!schedulesToUpdate.isEmpty()) {
            threadPool.submit(() -> this.updateBatchById(schedulesToUpdate));
            threadPool.submit(() -> saveOrUpdateAppointmentSlots(schedulesToUpdate));
        }

        // 添加新的排班信息
        if (!schedulesToAdd.isEmpty()) {
            threadPool.submit(() -> this.saveBatch(schedulesToAdd));
            threadPool.submit(() -> saveOrUpdateAppointmentSlots(schedulesToAdd));
        }

// 关闭线程池
        threadPool.shutdown();

        return new ResponseEntity<>(HttpStatus.OK);
    }

    public void saveOrUpdateAppointmentSlots(List<DoctorSchedule> doctorSchedules) {
        // 1. 提前查询所有相关医生的排班信息，减少数据库查询次数
        Set<Long> doctorIds = doctorSchedules.stream()
                .map(DoctorSchedule::getDoctorId)
                .collect(Collectors.toSet());
        List<SysDoctor> doctors = sysDoctorService.listByIds(doctorIds);

        // 2. 使用Map来存储排班日期和排号时间的关系，减少重复计算
        Map<String, List<AppointmentSlots>> scheduleMap = new HashMap<>();

        // 3. 遍历医生排班信息，构建排号时间数据
        for (DoctorSchedule doctorSchedule : doctorSchedules) {
            SysDoctor doctor = doctors.stream()
                    .filter(d -> d.getDoctorId().equals(doctorSchedule.getDoctorId()))
                    .findFirst()
                    .orElse(null);

            if (doctor == null) {
                continue; // 如果找不到医生信息，跳过当前排班
            }

            // 处理上午和下午的时间段
            if (doctorSchedule.getIsMorning()){
                processTimeSlots(doctorSchedule, doctor, scheduleMap, true); // 上午

            }
            if (doctorSchedule.getIsAfternoon()){
                processTimeSlots(doctorSchedule, doctor, scheduleMap, false); // 下午
            }
        }

        // 4. 批量删除旧的排号时间
        Set<Long> slotsToDelete = scheduleMap.values().stream()
                .flatMap(List::stream)
                .filter(Objects::nonNull) // 检查AppointmentSlots对象是否为null
                .map(AppointmentSlots::getId)
                .filter(Objects::nonNull) // 检查ID是否为null
                .collect(Collectors.toSet());
        // 分割任务并提交到线程池
        List<Future<?>> futures = new ArrayList<>();

        // 使用线程池来处理数据库操作
        ExecutorService threadPool = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池

        if (slotsToDelete != null && !slotsToDelete.isEmpty()) {
            futures.add(threadPool.submit(() -> appointmentSlotsMapper.deleteBatchIds(slotsToDelete)));
//            appointmentSlotsMapper.deleteBatchIds(slotsToDelete);
        }


        // 5. 批量保存新的排号时间
        List<AppointmentSlots> newSlots = scheduleMap.values().stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
//        appointmentSlotsService.saveBatch(newSlots);
        futures.add(threadPool.submit(() -> appointmentSlotsService.saveBatch(newSlots)));

        // 等待所有任务完成
        for (Future<?> future : futures) {
            try {
                future.get();
            } catch (InterruptedException | ExecutionException e) {
                // 处理异常
            }
        }

        // 关闭线程池
        threadPool.shutdown();
    }

    private void processTimeSlots(DoctorSchedule doctorSchedule, SysDoctor doctor,
                                  Map<String, List<AppointmentSlots>> scheduleMap, boolean isMorning) {
        // 根据排班日期和时间段生成排号时间
        Map<Integer, String> dailySchedule = TimeUtils.getDailySchedule(
                doctorSchedule.getScheduleDate(),
                isMorning ? doctorSchedule.getMorningStartTime() : doctorSchedule.getAfternoonStartTime(),
                isMorning ? doctorSchedule.getMorningEndTime() : doctorSchedule.getAfternoonEndTime(),
                doctor.getIntervalMinutes()
        );

        String key = generateKey(doctorSchedule.getDoctorId(), doctor.getDepartmentId(), doctorSchedule.getScheduleDate());
        List<AppointmentSlots> slots = scheduleMap.getOrDefault(key, new ArrayList<>());

        for (Map.Entry<Integer, String> entry : dailySchedule.entrySet()) {
            AppointmentSlots slot = new AppointmentSlots();
            slot.setDoctorId(doctorSchedule.getDoctorId());
            slot.setScheduleDate(doctorSchedule.getScheduleDate());
            slot.setDepartmentId(doctor.getDepartmentId());
            slot.setAppointmentTime(entry.getValue());
            slot.setIsMorning(isMorning);
            slot.setRowNum(entry.getKey());
            slots.add(slot);
        }

        scheduleMap.put(key, slots);
    }

    private String generateKey(Long doctorId, Long departmentId, LocalDate scheduleDate) {
        return doctorId + "-" + departmentId + "-" + scheduleDate.toString();
    }


    @Override
    public List<DoctorScheduleDto> getCurrentAll(DoctorScheduleQueryCriteria criteria) {
        //查询前端传回来的数据
        String date = criteria.getDate();
        DateTime parse = DateUtil.parse(date, "yyyy-MM");
        //获取月份的每一天的对应的日子类型集合
        DateTime beginOfMonth = DateUtil.beginOfMonth(parse);
        DateTime endOfMonth = DateUtil.endOfMonth(parse);
        String currentUsername = SecurityUtils.getCurrentUsername();
        System.out.println(currentUsername);
        if ("admin".equals(currentUsername)){
            List<User> users = userMapper.selectList(null);
            List<DoctorSchedule> doctorSchedules = doctorScheduleMapper.selectList(new LambdaQueryWrapper<DoctorSchedule>().between(DoctorSchedule::getScheduleDate, beginOfMonth, endOfMonth));
            return getScheduleVos(doctorSchedules,users);
        }else {
            // 返回当前用户的排班
            List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getUsername, currentUsername));
            List<DoctorSchedule> doctorSchedules = doctorScheduleMapper.selectList(
                    new LambdaQueryWrapper<DoctorSchedule>().eq(DoctorSchedule::getDoctorId,users.get(0).getId()).between(DoctorSchedule::getScheduleDate, beginOfMonth, endOfMonth));

            return getScheduleVos(doctorSchedules, users);
        }
    }
    private List<DoctorScheduleDto> getScheduleVos(List<DoctorSchedule> doctorSchedules, List<User> users) {
        List<DoctorScheduleDto> scheduleVos = new ArrayList<>();
        for (DoctorSchedule schedule : doctorSchedules) {
            DoctorScheduleDto doctorScheduleDto = new DoctorScheduleDto();
            BeanUtil.copyProperties(schedule,doctorScheduleDto);
            if (users.size() == 1){
                doctorScheduleDto.setNickName(users.get(0).getNickName());
            }else {
                doctorScheduleDto.setNickName(users.stream().filter(p -> p.getId().equals(schedule.getDoctorId())).findFirst().get().getNickName());
            }
//            doctorScheduleDto.setScheduleDate(schedule.getScheduleDate());
//            doctorScheduleDto.setIsAfternoon(schedule.getIsAfternoon());
//            doctorScheduleDto.setIsMorning(schedule.getIsMorning());
//            doctorScheduleDto.setAfternoonStartTime(schedule.getAfternoonStartTime());
//            doctorScheduleDto.setAfternoonEndTime(schedule.getAfternoonEndTime());
//            doctorScheduleDto.setMorningStartTime(schedule.getMorningStartTime());
//            doctorScheduleDto.setMorningEndTime(schedule.getMorningStartTime());
            scheduleVos.add(doctorScheduleDto);
        }
        return scheduleVos;
    }
}